{{define "/chat/foot.shtml"}}
<script>
// 上传图片
function upload(dom) {
  uploadfile("upload", dom, function(res) {
    if (res.code == 200) {
      app.sendpicmsg(res.data);
    } else {
      app.reset();
    }
  });
}
var app = new Vue({
  el:"#pageapp",
  data: {
    usermap: {},
    friends: [],
    communitys: [],
    profile: {
      avatar: "",
      nickname: "",
      memo: "",
    },
    webSocket: {},
    win: "main",
    txtmsg: "",
    panelstat: "kbord",
    txtstat: "kbord",
    title: "",
    doutu:{
      config: {
        "baseurl":"/asset/plugins/doutu/",
        "pkgids":["mkgif","emoj"]
      },
      packages: [],
      choosed:{"pkgid":"emoj","assets":[],"size":"small"}
    },
    msglist: [],
    // msg消息体
    msgcontext:{
      dst_id: 10,
      msg_type: 10,
      user_id: userId()
    },
    plugins:[
      {
          icon: "/asset/images/upload.png",
          name: "照片",
          id: "upload",
          slot: "<input accept=\"image/gif,image/jpeg,,image/png\" type=\"file\" onchange=\"upload(this)\" class='upload' />"
      },
      {
          icon: "/asset/images/camera.png",
          name: "拍照",
          id: "camera",
          slot: "<input accept=\"image/*\" capture=\"camera\" type=\"file\" onchange=\"upload(this)\" class='upload' />"
      },
      {
          icon: "/asset/images/audiocall.png",
          name: "通话",
          id: "audiocall"
      },
      {
          icon: "/asset/images/videocall.png",
          name: "视频",
          id: "videocall"
      },
      {
          icon: "/asset/images/redpackage.png",
          name: "红包",
          id: "redpackage"
      },
      {
          icon: "/asset/images/exchange.png",
          name: "转账",
          id: "exchange"
      },
      {
          icon: "/asset/images/address.png",
          name: "位置",
          id: "address"
      },
      {
          icon: "/asset/images/person.png",
          name: "名片",
          id: "person"
      },
    ],
    timer: 0,
    recorder: {},
    allChunks: [],
    iscomplete: false,
    duration: 0,
  },
  created: function(){
    this.loadfriends();
    // this.loadcommunitys();
    this.loaddoutures();
    // 用户信息
    var user = userInfo();
    if (!!user) {
      this.profile.avatar = user.avatar;
      this.profile.nickname = user.nickname;
      this.profile.memo = user.memo;
      var url = "ws://"+location.host+"/chat?id="+userId()+"&token=" +user.token;
      this.webSocket = new WebSocket(url);
      this.initwebsocket();
    }
  },
  methods:{
    playaudio:function(url){
      document.getElementById('audio4play').src = url;
      document.getElementById('audio4play').play();
    },
    // 录音
    startrecorder: function() {
      var types = [
        "video/webm",
        "audio/webm",
        "video/webm\;codecs=vp8",
        "video/webm\;codecs=daala",
        "video/webm\;codecs=h264",
        "audio/webm\;codecs=opus",
        "video/mpeg"
      ];
      var suportType = "";
      for (var i in types) {
        if (MediaRecorder.isTypeSupported(types[i])) {
            suportType = types[i];
            break;
        }
      }
      if (!suportType) {
        mui.toast("编码不支持");
        return;
      }
      this.duration = new Date().getTime();
			if (navigator.mediaDevices === undefined) {
   			navigator.mediaDevices = {};
			}
			if (navigator.mediaDevices.getUserMedia === undefined) {
				navigator.mediaDevices.getUserMedia = function (constraints) {
					var getUserMedia = navigator.webkitGetUserMedia
						|| navigator.mozGetUserMedia
						|| navigator.msGetUserMedia;
					if (!getUserMedia) {
						return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
					}
					return new Promise(function(resolve, reject) {
						getUserMedia.call(navigator, constraints, resolve, reject);
					});
				}
			}
      let audioTarget = document.getElementById('audio');
      navigator.mediaDevices.getUserMedia({audio: true})
			.then((stream) => {
      	this.recorder = new MediaRecorder(stream);
        audioTarget.srcObject = stream;
        this.recorder.ondataavailable = (event) => {
          uploadblob("upload", event.data, ".mp3", res => {
            var duration = Math.ceil((new Date().getTime() - this.duration) / 1000);
            this.sendaudiomsg(res.data, duration);
          });
        }
        this.recorder.start();
      }).
			catch(function(err) {
      	mui.toast(err.msg);
      });
    },
    // 停止录音
    stoprecorder: function() {
      if (typeof this.recorder.stop == "function") {
        this.recorder.stop();
      }
    },
    dispatchplugin: function(item) {
      switch (item.id) {
        case "upload":
        case "camera":
          break;
        default:
          mui.toast("系统暂不支持,请自行扩展")
      }
    },
    // 重置
    reset: function() {
      this.panelstat = "kbord";
      this.txtstat = "kbord";
      this.txtmsg = "";
    },
    createmsgcontext: function() {
      return JSON.parse(JSON.stringify(this.msgcontext))
    },
    loaddoutures: function(){
      var res=[];
      var config = this.doutu.config;
      for(var i in config.pkgids){
        res[config.pkgids[i]]=(config.baseurl+"/"+config.pkgids[i]+"/info.json")
      }
      var that = this;
      for(var id in res){
        // console.log("res[i]",id,res[id])
        post(res[id],{},function(pkginfo){
          // console.log("post res[i]",id,res[id],pkginfo)
          var baseurl= config.baseurl+"/"+pkginfo.id+"/"
          for(var j in pkginfo.assets){
              pkginfo.assets[j] = baseurl+pkginfo.assets[j];
            }
          pkginfo.icon = baseurl + pkginfo.icon;
          that.doutu.packages.push(pkginfo)
          if(that.doutu.choosed.pkgid==pkginfo.id){
            that.doutu.choosed.assets=pkginfo.assets;
          }
        })
      }
    },
    showweixin:function(){
      mui.alert("请加微信号jiepool-winlion索取")
    },
    // 显示消息
    showmsg: function(user, msg) {
      var data = {}
      data.ismine = userId() == msg.user_id;
      data.user = user;
      data.msg = msg;
      this.msglist = this.msglist.concat(data)
      // console.log(this.msglist);
      this.reset();
      var that = this;
      that.timer = setTimeout(function() {
        window.scrollTo(0, document.getElementById("convo").offsetHeight);
        clearTimeout(that.timer);
      }, 100);
    },
    // startrecord: function(){
    // },
    // 发送文本消息
    sendtxtmsg: function(txt){
        //{id:1,userid:2,dstid:3,cmd:10,media:1,content:"hello"}
        var msg = this.createmsgcontext();
        msg.media = 1;
        msg.content = txt;
        this.showmsg(userInfo(), msg);
        this.webSocket.send(JSON.stringify(msg))
    },
    // 发送图片消息
    sendpicmsg: function(picurl) {
      //{id:1,userid:2,dstid:3,cmd:10,media:4,url:"http://www.baidu.com/a/log,jpg"}
      var msg = this.createmsgcontext();
      msg.media = 4;
      msg.url = picurl;
      this.showmsg(userInfo(), msg)
      // console.log(msg);
      this.webSocket.send(JSON.stringify(msg))
    },
    // 发送语音消息
    sendaudiomsg: function(url,num) {
      //{id:1,userid:2,dstid:3,cmd:10,media:3,url:"http://www.a,com/dsturl.mp3",anount:40}
      var msg = this.createmsgcontext();
      msg.media = 3;
      msg.url = url;
      msg.amount = num;
      this.showmsg(userInfo(),msg)
      this.webSocket.send(JSON.stringify(msg))
    },
    // 单聊
    singlemsg: function(user) {
      this.win = "single";
      this.title = "和"+user.nickname+"聊天中";
      this.msgcontext.dst_id = user.id;
      this.msgcontext.msg_type = 10;
    },
    // 群聊
    groupmsg: function(group) {
      this.win = "group";
      this.title = group.name;
      this.msgcontext.dst_id = group.id;
      this.msgcontext.msg_type = 11;
    },
    // 加载用户信息
    loaduserinfo: function(user_id, cb) {
      var userinfo = this.usermap[user_id];
      if (!userinfo) {
        post("user/find", {id: user_id}, function(res) {
          cb(res.data);
          this.usermap[user_id] = res.data;
        }.bind(this))
      } else {
          cb(userinfo)
      }
    },
    // 接收消息处理
    onmessage: function(data) {
      this.loaduserinfo(data.user_id, function(user) {
        this.showmsg(user, data)
      }.bind(this))
    },
    // websocket事件处理
    initwebsocket: function() {
      this.webSocket.onmessage = function(evt) {
        this.onmessage(JSON.parse(evt.data));
      }.bind(this)
      this.webSocket.onclose = function (evt) {
        console.log(evt.data)
      }
      this.webSocket.onerror = function (evt) {
        console.log(evt.data)
      }
    },
    // sendmsg:function(){
    // },
    // 加载好友列表
    loadfriends: function(){
      var that = this;
      post("contact/friend",
        {
           user_id: userId()
        }, function(res) {
          that.friends = res.rows || [];
          var usermap = that.usermap;
          for (var i in res.rows) {
            usermap[res.rows[i].id] = res.rows[i];
          }
          this.usermap = usermap;
        }.bind(this))
    },
    // loadcommunitys:function(){
    //   var that = this;
    //   post("contact/community",{userid:userId()},function(res){
    //       that.communitys = res.rows ||[];
    //     })
    // },
    // 添加好友
    addfriend: function() {
      var that = this;
      mui.prompt('', '请输入好友ID', '加好友', ['取消','确认'], function (e) {
        if (e.index == 1) {
          if (isNaN(e.value) || e.value <= 0) {
            mui.toast('格式错误');
          } else {
            that._addfriend(e.value)
          }
        } else {
          mui.toast('不加好友了');
        }
      },'div');
      document.querySelector('.mui-popup-input input').type = 'number';
    },
    _addfriend: function(dstId) {
        var user = userInfo();
        post("contact/add",{
            dst_id: dstId,
            user_id: user.id,
            pic: user.avatar,
            content: user.nickname,
            memo: "请求加你为好友"
          },
          function(res) {
            if (res.code == 200) {
              mui.toast("添加成功");
              that.loadfriends();
            } else {
              mui.toast(res.msg);
            }
          })
      },
    // _joincomunity:function(dstobj){
    //   var that = this;
    //   post("user/joincommunity",{dstid:dstobj},function(res){
    //       if(res.code==200){
    //           mui.toast("添加成功");
    //           that.loadcommunitys();
    //         }else{
    //             mui.toast(res.msg);
    //           }
    //     })
    // },
    // 群
    joincomunity: function() {
      console.log("join");
      return;
      var that = this;
      mui.prompt('','请输入群号','加群',['取消','确认'],function (e) {
        if (e.index == 1) {
            if (isNaN(e.value) || e.value <= 0) {
                mui.toast('格式错误');
              }else{
                  //mui.toast(e.value);
                  that._joincomunity(e.value)
                }
          }else{
              //mui.toast('您取消了入库');
            }
      },'div');
      document.querySelector('.mui-popup-input input').type = 'number';
    },
    // 退出登录
    quit: function () {
      sessionStorage.removeItem("userid")
      sessionStorage.removeItem("userinfo");
      location.href="/user/login.shtml";
    }
  },
  watch:{
    "win": function(n,o) {
      if (n!="main") {
        document.getElementById("menubar").style.display = "none";
      } else {
        document.getElementById("menubar").style.display = "block";
      }
    }
  }
})
</script>
{{end}}
